/**
 * Test Streaming API
 * 
 * This script tests the streaming API endpoint to verify it's working correctly
 */

const BASE_URL = 'http://localhost:3000';

async function testStreaming() {
  console.log('🧪 Testing Streaming API...\n');

  const request = {
    prompt: 'Say "Hello, World!" and explain what you are.',
    options: {
      model: 'claude-sonnet-4',
      maxTurns: 10,
      includePartialMessages: true,
    },
  };

  console.log('📤 Sending request:', JSON.stringify(request, null, 2));
  console.log('\n📡 Streaming response:\n');

  try {
    const response = await fetch(`${BASE_URL}/api/agent/query/streaming`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(request),
    });

    if (!response.ok) {
      console.error(`❌ HTTP error! status: ${response.status}`);
      const text = await response.text();
      console.error('Response:', text);
      return;
    }

    console.log('✅ Connection established, reading stream...\n');

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';
    let messageCount = 0;

    while (true) {
      const { done, value } = await reader.read();
      if (done) {
        console.log('\n✅ Stream completed');
        break;
      }

      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split('\n');
      buffer = lines.pop() || '';

      for (const line of lines) {
        if (line.startsWith('data: ')) {
          const data = line.slice(6);
          if (data === '[DONE]') {
            console.log('\n✅ Received [DONE] signal');
            return;
          }
          try {
            const parsed = JSON.parse(data);
            messageCount++;
            console.log(`\n📨 Message ${messageCount}:`);
            console.log(JSON.stringify(parsed, null, 2));
            
            if (parsed.type === 'assistant' && parsed.content) {
              console.log(`\n💬 Assistant: ${parsed.content}`);
            }
          } catch (e) {
            console.error('❌ Failed to parse SSE data:', e);
            console.error('Raw data:', data);
          }
        }
      }
    }

    console.log(`\n📊 Total messages received: ${messageCount}`);
  } catch (error) {
    console.error('❌ Error:', error.message);
    console.error(error);
  }
}

// Run the test
testStreaming();

